use crate::math::{ Vector2u};
use winit::{
    dpi::PhysicalSize,
    
    event_loop::{EventLoop},
    window::{ Window, WindowBuilder},
};



use super::window_config::MainWindowConfig;



pub struct WinitWindow {
    window: Window,
    
}

#[cfg(target_arch="wasm32")]
use wasm_bindgen::prelude::*;


impl WinitWindow {
    pub fn new(event_loop: &EventLoop<()>,config:&MainWindowConfig) -> Self {

        cfg_if::cfg_if! {
            if #[cfg(target_arch = "wasm32")] {
                std::panic::set_hook(Box::new(console_error_panic_hook::hook));
                // console_log::init_with_level(log::Level::Warn).expect("Couldn't initialize logger");
            } 
        }

        let window            = WindowBuilder::new()
                                            .with_inner_size(PhysicalSize::new(config.width,config.height))
                                            .with_title(&config.title)
                                            .build(&event_loop)
                                            .unwrap();
        #[cfg(target_arch = "wasm32")]
        {
            // Winit prevents sizing with CSS, so we have to set
            // the size manually when on web.
            use winit::dpi::PhysicalSize;
            window.set_inner_size(PhysicalSize::new(config.width, config.height));
            
            use winit::platform::web::WindowExtWebSys;
            web_sys::window()
                .and_then(|win| win.document())
                .and_then(|doc| {
                    let dst = doc.get_element_by_id("viewport")?;
                    let canvas = web_sys::Element::from(window.canvas());
                    dst.append_child(&canvas).ok()?;
                    Some(())
                })
                .expect("Couldn't append canvas to document body.");
        }
                                    
                               
        Self { window  }
    }

    pub fn get_window(&self) -> &Window {
        &self.window
    }

    pub fn get_size(&self) -> Vector2u {
        let size = self.window.inner_size();
        Vector2u::new(size.width, size.height)
    }

    pub fn set_window_size(&self,size:Vector2u) {
        self.window.set_inner_size(PhysicalSize::new(size.x,size.y));
    }

    pub fn set_title(&mut self,name:& str) {
        self.window.set_title(name)
    }
}


